# coding=UTF-8
from __future__ import division
import os

from PIL import Image
def bathresizeImg(paths):
   for root, sub_dirs, files in os.walk(paths):
    for special_file in files:
        if special_file.startswith(".DS_Store"):
            continue;
        if special_file.endswith('.jpg'):
              filepath= os.path.join(root,special_file)
              resize(root,filepath)

   return 0

def resize(dir,path):
    height=32
    width=32
    new_dir=dir.replace("fruitimgs","samebigfruit")
    newpath=path.replace("fruitimgs","samebigfruit")
    if not  os.path.exists(new_dir):
        os.makedirs(new_dir)
    try:
        im = Image.open(path)
        (x, y) = im.size

        if(x>y):
            new_width=int(float(x/y)*width)
            new_height=height;
            out = im.resize((new_width, new_height), Image.ANTIALIAS)
            region=(int(new_width/2-width/2),0,int(new_width/2-width/2+width),height)
            out=out.crop(region)
        else:
            new_height=int(y/x*height)
            new_width=width
            out = im.resize((new_width, new_height), Image.ANTIALIAS)
            region=(0,int(new_height/2-height/2),width,int(new_height/2-height/2+height))
            out = out.crop(region)
        out.save(newpath)
    except:
        pass
        return


path="/work/scrapy/data/fruitimgs"
bathresizeImg(path)

